package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.RecipeDraft;
import com.recipedb.recipedb.service.RecipeDraftService;
import com.recipedb.recipedb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/recipedraft")
public class RecipeDraftController {

    @Autowired
    private RecipeDraftService service;

    @Autowired
    private UserService userService;

    @PostMapping
    public RecipeDraft add(@RequestBody RecipeDraft entity) {
        return service.save(entity);
    }

    @DeleteMapping
    public void delete(@RequestParam Long id) {
        service.deleteById(id);
    }

    @GetMapping("/all")
    public List<RecipeDraft> getAll() {
        return service.findAll();
    }

    @GetMapping("/by-user")
    public List<RecipeDraft> getDraftsByUserId(@RequestParam Long userId, Authentication authentication) {
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!currentUserId.equals(userId)) throw new AccessDeniedException("无权查询他人的草稿");
        return service.findByUserId(userId);
    }

    @GetMapping("/single")
    public RecipeDraft getDraftById(@RequestParam Long id, Authentication authentication) {
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        RecipeDraft draft = service.findById(id).orElseThrow(() -> new RuntimeException("草稿不存在"));
        if (!draft.getUserId().equals(currentUserId)) throw new AccessDeniedException("无权访问该草稿");
        return draft;
    }

    @PatchMapping("/{id}")
    public RecipeDraft update(@PathVariable Long id, @RequestBody RecipeDraft partialEntity, Authentication authentication) {
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        RecipeDraft draft = service.findById(id).orElseThrow(() -> new RuntimeException("草稿不存在"));
        if (!draft.getUserId().equals(currentUserId)) throw new AccessDeniedException("无权访问该草稿");

        partialEntity.setUserId(currentUserId); // 禁止修改 userId
        return service.updateById(id, partialEntity);
    }

    @PutMapping("/{id}")
    public RecipeDraft replace(@PathVariable Long id, @RequestBody RecipeDraft incoming, Authentication authentication) {
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        RecipeDraft existing = service.findById(id).orElseThrow(() -> new RuntimeException("草稿不存在"));
        if (!existing.getUserId().equals(currentUserId)) throw new AccessDeniedException("无权访问该草稿");

        // 合并 PUT 数据（保留 userId）
        RecipeDraft merged = com.recipedb.recipedb.util.MergeUtils.mergeForPut(existing, incoming);
        merged.setUserId(currentUserId);

        return service.updateById(id, merged);
    }

    @GetMapping("/by-user/search")
    public Page<RecipeDraft> searchDrafts(@RequestParam Long userId,
                                          @RequestParam(required = false) String keyword,
                                          @RequestParam(required = false) String tag,
                                          @RequestParam(required = false) String category,
                                          @RequestParam(required = false) String ingredient,
                                          @RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "10") Integer pageSize,
                                          Authentication authentication) {

        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!currentUserId.equals(userId)) throw new AccessDeniedException("无权查询他人的草稿");

        return service.searchDrafts(userId, keyword, tag, category, ingredient, pageNum, pageSize);
    }

    // ========== 新增接口：上传封面或步骤图片 ==========
    @PostMapping("/upload-image")
    public String uploadImage(@RequestParam Long draftId,
                              @RequestParam int stepId,
                              @RequestParam MultipartFile file,
                              Authentication authentication) {

        RecipeDraft draft = service.findById(draftId).orElseThrow(() -> new RuntimeException("草稿不存在"));
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!draft.getUserId().equals(currentUserId)) throw new AccessDeniedException("无权上传该草稿图片");

        return service.uploadDraftImage(draftId, stepId, file);
    }

    @GetMapping("/cover-url")
    public String getCoverUrl(@RequestParam Long draftId, Authentication authentication) {
        RecipeDraft draft = service.findById(draftId).orElseThrow(() -> new RuntimeException("草稿不存在"));
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!draft.getUserId().equals(currentUserId)) throw new AccessDeniedException("无权访问");
        return service.getCoverUrl(draft);
    }

    @GetMapping("/step-urls")
    public List<String> getStepUrls(@RequestParam Long draftId, Authentication authentication) {
        RecipeDraft draft = service.findById(draftId).orElseThrow(() -> new RuntimeException("草稿不存在"));
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!draft.getUserId().equals(currentUserId)) throw new AccessDeniedException("无权访问");
        return service.getStepUrls(draft);
    }
}
